package p18.code;

import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;

public class ReaderThread extends Thread {

    private final Socket socket;//声明一个套接字
    private final InputStream in;//声明一个输入楼

    public ReaderThread(Socket socket) throws IOException {
        this.socket = socket;//获得套接字
        this.in = socket.getInputStream();//获得套接字输入流
    }

    /**
     * 中断任务
     */
    public void interrupt() {
        try{
            socket.close();//关闭套接字
        }catch(IOException ignored){

        }finally{
            super.interrupt();//中断上层
        }
    }

    public void run(){
        try{
            byte[] buf = new byte[1024];
            while(true) {
                int count = in.read(buf);
                if(count<0) break;
                else if(count>0)
                    processBuffer(buf,count);
            }
        }
        catch(IOException ignored){
            interrupt();
        }
    }

    public void processBuffer(byte[] buf,int count){
        //处理buf...
    }

}
